package com.gin.kotlin.no_gay_alliance.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.util.Log
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.databinding.ActivityLoginBinding
import com.gin.nga.cookie.NgaCookie
import java.net.URLDecoder


/**
 * 登录活动
 */
class LoginActivity : AbstractBindingActivity<ActivityLoginBinding>() {

    private lateinit var viewClient: WebViewClient
    private lateinit var chromeClient: WebChromeClient

    /**
     * 解析意图
     * @param intent Intent?
     */
    override fun handleIntent(intent: Intent) {
    }

    /**
     * onCreate方法的后续操作，如 [AbstractBindingActivity.registerLauncher]， 或 [AbstractBindingActivity.attachTabLayout]
     */
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate() {

        // 初始化客户端

        this.viewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                //设置在webView点击打开的新网页在当前界面显示,而不跳转到新的浏览器中
                view?.loadUrl(request?.url.toString())
                return true
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                // 清空cookie
                CookieManager.getInstance().removeAllCookies(null)
                CookieManager.getInstance().flush()
            }
        }


        this.chromeClient = object : WebChromeClient() {
            override fun onJsConfirm(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                val cookie = url?.let { CookieManager.getInstance().getCookie(it) }.let { URLDecoder.decode(it, NgaCookie.CHARSET) }

                Log.d(TAG, "onJsConfirm: $cookie")

                if (NgaCookie.isLegal(cookie)) {
                    val ngaCookie = NgaCookie(cookie)
                    val c = ngaCookie.toString()
                    Log.i(TAG, "username: ${ngaCookie.username} cookie: $c")
                    val intent = Intent()
                    intent.putExtra(KEY_COOKIE, c)
                    setResult(200, intent)
                    finish()
                }

                return super.onJsConfirm(view, url, message, result)
            }
        }


        //开始请求
        val webView = b?.webView ?: return

        webView.clearCache(true)
        webView.clearHistory()
        webView.webViewClient = viewClient
        webView.webChromeClient = chromeClient
        webView.settings.javaScriptEnabled = true
        webView.loadUrl(LOGIN_URL)
    }

    override fun finish() {
        // 处理报错
        (window.decorView as ViewGroup).removeAllViews()
        super.finish()
    }

    override fun onPause() {
        super.onPause()
        b?.webView?.onPause()
    }

    override fun onResume() {
        b?.webView?.onResume()
        super.onResume()
    }

    override fun onDestroy() {

        (b?.webView?.parent as ViewGroup).removeView(b?.webView)
        b?.webView?.removeAllViews()

        b?.webView?.destroy()
        super.onDestroy()
    }


    companion object {
        /**
         * 登录地址
         */
        private const val LOGIN_URL: String = "https://bbs.nga.cn/nuke.php?__lib=login&__act=account&login"
        private val TAG = LoginActivity::class.java.simpleName
        const val KEY_COOKIE = "cookie"
    }
}